package cn.xrfzh.common.utils;

import cn.xrfzh.common.constants.AESAlgorithmConstant;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class EncryptionService {

    private final String secretKey;

    private final String iv;

    public EncryptionService(String secretKey, String iv) {
        this.secretKey = secretKey;
        this.iv = iv;
    }

    // AES加密
    public String encrypt(String text) throws Exception {
        SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes());
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
        byte[] encryptedBytes = cipher.doFinal(text.getBytes());
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    // AES解密
    public String decrypt(String cipherText) throws Exception {
        SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes());
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(cipherText));
        return new String(decryptedBytes);
    }

    public static void main(String[] args) throws Exception {
        EncryptionService encryptionService = new EncryptionService(AESAlgorithmConstant.SECRET_KEY, AESAlgorithmConstant.IV);
        String username = encryptionService.encrypt("997892");
        System.out.println("username: " + username);
        String password = encryptionService.encrypt("admin123456");
        System.out.println("password: " + password);
//        String decryptedText = encryptionService.decrypt(encryptedText);
//        System.out.println("Decrypted Text: " + decryptedText);
    }

}
